import {articleSaveReq} from "@/service/resource.ts";
import {SuccessCode} from "@/utils/request.ts";
import {CloseOutlined} from "@ant-design/icons";
import EditorJS, {OutputData} from "@editorjs/editorjs";
import Header from '@editorjs/header';
// @ts-ignore
import List from '@editorjs/list';
import {message} from "antd";
import {useEffect, useRef, useState} from "react";
import styles from "./index.module.less"


interface EditModalProps {
    article?: API.ArticleListRespItem
    onClose: () => void
}

const EditModal = (props: EditModalProps) => {
    const [saveStatus, setSaveStatus] = useState<'Saved' | 'Not Save'>('Saved')
    const editorRef = useRef<EditorJS | null>(null);
    const [name, setName] = useState<string>('')

    useEffect(() => {
        setName(props.article?.name ?? "")
        if (!editorRef.current) {
            editorRef.current = new EditorJS({
                holder: 'editorjs',
                autofocus: true,
                data: props.article?.content ? JSON.parse(props.article.content) as OutputData : {
                    blocks: [
                        {
                            type: "paragraph",
                            data: {
                                text: "开始你的创作吧！"
                            },
                        }
                    ]
                } as OutputData,
                tools: {
                    header: {
                        // @ts-ignore
                        class: Header,
                        inlineToolbar: ['link']
                    },
                    list: {
                        class: List,
                        inlineToolbar: true
                    }
                },
                onReady: () => {
                    // console.log('Editor.js is ready!');
                },
                onChange: async () => {
                    if (!editorRef.current) return;
                    const outputData = await editorRef.current.save();
                    onSave(outputData).then(res => {
                        if (res.code === SuccessCode) {
                            setSaveStatus("Saved")
                        } else {
                            message.error("page.save.error")
                            setSaveStatus("Not Save")
                        }
                    });
                },
            });
        }

        return () => {
            if (editorRef.current) {
                editorRef.current?.destroy();
                editorRef.current = null;
            }

        };
    }, [props.article]);


    const onSave = async (outputData: OutputData) => {
        return await articleSaveReq({...props.article, content: JSON.stringify(outputData), name: name})
    }

    // 关闭窗口
    const onClose = () => {
        editorRef.current?.save().then(res => {
            onSave(res).then(res => {
                if (res.code == SuccessCode) {
                    props.onClose()
                }
            })
        })
    }

    return (
        <div
            className={`${styles.ArticleEdit} `}
        >
            <div className={styles.Header}>
                <input className={styles.Title}
                       value={name}
                       placeholder={"文章标题"}
                       onChange={(event) => {
                           setName(event.target.value)
                       }}/>

                <div className={styles.Right}>
                    <div className={styles.Status}>
                        {saveStatus}
                    </div>
                    <CloseOutlined style={{fontSize: 20}} onClick={onClose}/>
                </div>
            </div>
            <div className={styles.Content}>
                <div id="editorjs" className={styles.Editor}></div>

            </div>
        </div>
    );
};

export default EditModal;
